/*
 * @Description: 向某条规则下添加用户、组弹窗
 * @Author: Rfan
 * @Date: 2022-04-08 09:07:14
 * @LastEditTime: 2022-05-25 09:01:42
 */

import { useCallback, useEffect, useState } from 'react';
import { Button, message, Modal, Tabs } from 'antd';
import type { FC } from 'react';
import {
  AddUserDialogContextProvider,
  useAddUserDialogContext
} from './contexts/AddUserDialogContext';
import GroupPane from './components/GroupPane';
import UserPane from './components/UserPane';
import { addNormalRuleUser } from '@/api/right';
import type { ICommonDialog } from '@/interfaces/global';

const { TabPane } = Tabs;

interface IAddUserDialogProps extends ICommonDialog {
  ruleId: number;
  tabType: number;
}

const AddUserDialogComp: FC<IAddUserDialogProps> = (props) => {
  console.log('AddUserDialogComp', props.tabType);

  const { visible, ruleId, tabType = 0, onClose } = props;
  const { selectDepartments, selectUsers, setSelectDepartments, setSelectUsers } =
    useAddUserDialogContext();
  const [activeTab, setActiveTab] = useState(tabType);
  const memoizedClose = useCallback((list?) => {
    setSelectDepartments([]);
    setSelectUsers([]);
    onClose(list);
  }, []);

  useEffect(() => {
    if (visible) {
      if (tabType !== activeTab) {
        setActiveTab(tabType);
      }
    }
  }, [visible]);

  const onCancel = () => {
    memoizedClose();
  };

  const addUsers = () => {
    const idList = activeTab === 1 ? [...selectDepartments] : [...selectUsers];
    if (idList.length <= 0) {
      message.warning('请先选择用户或部门');
      return;
    }
    const params = {
      ruleId,
      userInfoList: idList.map((item: number) => {
        return {
          [activeTab === 1 ? 'departmentId' : 'userId']: item,
          granteeType: activeTab // 暂时写死，后期tab改为受控，通过激活tab获取
        };
      })
    };
    addNormalRuleUser(params).then((res) => {
      const { data } = res;
      memoizedClose(data || {});
    });
  };

  const changeTabs = (activeKey: string) => {
    setActiveTab(parseInt(activeKey, 10));
  };

  return (
    <Modal
      title="选择人员"
      visible={visible}
      width={600}
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          取消
        </Button>,
        <Button
          key="save"
          type="primary"
          onClick={() => {
            addUsers();
          }}
        >
          确认
        </Button>
      ]}
    >
      <Tabs activeKey={`${activeTab}`} onChange={changeTabs}>
        <TabPane tab="按组织选择" key="1">
          <GroupPane />
        </TabPane>
        <TabPane tab="按组织内成员选择" key="0">
          <UserPane />
        </TabPane>
      </Tabs>
    </Modal>
  );
};

const AddUserDialog = (props: any) => (
  <AddUserDialogContextProvider>
    {' '}
    <AddUserDialogComp {...props} />
  </AddUserDialogContextProvider>
);

export default AddUserDialog;
